package com.huahua.api.service.impl;

import com.dtflys.forest.sse.SSELinesMode;
import com.huahua.api.api.DmxApiClient;
import com.huahua.api.entity.dto.DmxApiRequestV2;
import com.huahua.api.service.DmxApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * DMX API 服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DmxApiServiceImpl implements DmxApiService {

    private final DmxApiClient dmxApiClient;

    @Value("${dmx.api.key:}")
    private String apiKey;

    @Override
    public Flux<String> chatCompletions(DmxApiRequestV2 request) {
        return Flux.create(sink -> {
            try {
                dmxApiClient.chatCompletionsSSE(apiKey, request)
                        .setOnMessage(event -> {
                            String data = event.data();
                            if (data != null && !data.isEmpty()) {
                                if ("[DONE]".equals(data.trim())) {
                                    sink.complete();
                                    return;
                                }

                                try {
                                    JSONObject json = JSONUtil.parseObj(data);
                                    JSONObject delta = json.getJSONArray("choices")
                                            .getJSONObject(0)
                                            .getJSONObject("delta");

                                    String content = delta.getStr("content");
                                    if (content != null) {
                                        sink.next(content);
                                    }
                                } catch (Exception e) {
                                    log.warn("解析响应数据失败: {}", data, e);
                                }
                            }
                        })
                        .setOnClose((event) -> {
                            log.debug("SSE连接关闭");
                            sink.complete();
                        })
                        .listen(SSELinesMode.SINGLE_LINE);
            } catch (Exception e) {
                log.error("调用DMX API失败", e);
                sink.error(e);
            }
        });
    }


}
